import os
import logging
import shutil

from utils.common import load_logging_config,dump_json
from consta import path_sep

def add_post_processor():
    name='ctc_decode_and_remove_tails'
    file='post_processors.pp1'
    if os.path.exists(file):
        if not os.path.abspath(file).startswith(os.path.abspath('post_processors')):
            target_pp_py=f'post_processors/{os.path.splitext(file.split("/")[-1])[0]}.py'
            if os.path.basename(target_pp_py) in os.listdir('post_processors'): # 存数据库里
                logging.error('后处理模块重名')
            shutil.copy(file,target_pp_py)
            modulename=target_pp_py[:-3].replace('/','.')
        else:
            modulename=os.path.relpath(file,'.').replace(path_sep,'.')
            modulename=modulename if not modulename.endswith('.py') else modulename[:-3]
    elif file!='':
        modulename=file if not file.endswith('.py') else file[:-3]
        modulename=modulename.replace('/','.')
    else:
        logging.error('后处理模块名不能为空')
    
    classname='ctc_decode_and_remove_tail'
    parameters=''
    attribute=''
    pp_json={
        'name':name,
        'modulename':modulename,
        'classname':classname,
        'parameters':parameters,
        'attribute':attribute
    }
    if not f'{pp_json["name"]}.json' in os.listdir('jsons/post_processors'):
        dump_json(pp_json,f'jsons/post_processors/{pp_json["name"]}.json')
    else:
        logging.error('后处理json文件重名，请重命名')

if __name__=='__main__':
    load_logging_config()
    add_post_processor()